﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Win32;
using System.Runtime.InteropServices;

namespace SkyShellEx.IconOverlay
{
    public static class ShellComRegister
    {


        public static void RegisterShellIconOverlayIdentifier(Type type)
        {
            using (RegistryKey approved = Registry.LocalMachine.CreateSubKey(
              @"Software\Microsoft\Windows\CurrentVersion\Shell Extensions\Approved",
              RegistryKeyPermissionCheck.ReadWriteSubTree))
            {
                approved.SetValue(type.GUID.ToString("B").ToUpper(), " _" + type.FullName);
            }

            using (RegistryKey key = Registry.LocalMachine.OpenSubKey(
              @"SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\ShellIconOverlayIdentifiers",
              RegistryKeyPermissionCheck.ReadWriteSubTree,
              System.Security.AccessControl.RegistryRights.FullControl))
            {
                using (RegistryKey sioi = key.CreateSubKey(" _" + type.FullName))
                {
                    sioi.SetValue(String.Empty, type.GUID.ToString("B").ToUpper());
                }
            }

            ShellMethods.SHChangeNotify(Enums.HChangeNotifyEventID.SHCNE_ASSOCCHANGED, Enums.HChangeNotifyFlags.SHCNF_IDLIST, IntPtr.Zero, IntPtr.Zero);

            ShellMethods.SHLoadNonloadedIconOverlayIdentifiers();

            //byte[] buffer = System.Text.Encoding.Unicode.GetBytes(@"C:\test2");
            //fixed (byte* p = buffer)
            //{
            //    IntPtr ptr = (IntPtr)p;
            //    ShellMethods.SHChangeNotify(Enums.HChangeNotifyEventID.SHCNE_UPDATEDIR, Enums.HChangeNotifyFlags.SHCNF_PATHA, ptr, IntPtr.Zero);
            //}
        }

        public static void UnregisterShellIconOverlayIdentifier(Type type)
        {
            using (RegistryKey key = Registry.LocalMachine.OpenSubKey(
              @"SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\ShellIconOverlayIdentifiers",
              RegistryKeyPermissionCheck.ReadWriteSubTree,
              System.Security.AccessControl.RegistryRights.FullControl))
            {
                key.DeleteSubKey(" _" + type.FullName, false);
            }

            using (RegistryKey approved = Registry.LocalMachine.OpenSubKey(
              @"Software\Microsoft\Windows\CurrentVersion\Shell Extensions\Approved",
              RegistryKeyPermissionCheck.ReadWriteSubTree,
              System.Security.AccessControl.RegistryRights.FullControl))
            {
                approved.DeleteValue(" _" + type.GUID.ToString("B").ToUpper(), false);
            }

            ShellMethods.SHChangeNotify(Enums.HChangeNotifyEventID.SHCNE_ATTRIBUTES, Enums.HChangeNotifyFlags.SHCNF_IDLIST, IntPtr.Zero, IntPtr.Zero);

            ShellMethods.SHLoadNonloadedIconOverlayIdentifiers();

           
        }
    }
}
